package com.gx.util.core.core;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
 */
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    private static final Logger log = LoggerFactory.getLogger(SpringContextHolder.class);


    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static <T> T getBean(String id) {
        return (T) applicationContext.getBean(id);
    }
    public static Map<String, Object> getBeans(Class<? extends Annotation> var1) {
        return applicationContext.getBeansWithAnnotation(var1);
    }


    @Override
    public void destroy() throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
//        logger.debug("注入ApplicationContext到SpringContextHolder:{}" + applicationContext);
//        if (SpringContextHolder.applicationContext != null) {
//            logger.info("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
//        }
        this.applicationContext = applicationContext; // NOSONAR
    }


}
